package com.googlecode.cococircus.client;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

public class EditCanvasEntry implements EntryPoint {
	Canvas canvas;
	Context2d context;
	static final int canvasHeight = 300;
	static final int canvasWidth = 300;

	public void onModuleLoad() {
		// 通常IE8等でサポートされていないキャンバス要素がサポートできるかどうかをチェック。
		if(isSupport()){
			initExCanvas();
		}

		canvas = Canvas.createIfSupported();

		// サポートされない場合は、上記でNULLが返却される。
		if (canvas == null) {
			RootPanel
					.get()
					.add(new Label(
							"Sorry, your browser doesn't support the HTML5 Canvas element"));
			return;
		}

		canvas.setStyleName("mainCanvas");
		canvas.setWidth(canvasWidth + "px");
		canvas.setCoordinateSpaceWidth(canvasWidth);

		canvas.setHeight(canvasHeight + "px");
		canvas.setCoordinateSpaceHeight(canvasHeight);

		RootPanel.get().add(canvas);
		context = canvas.getContext2d();

		final Timer timer = new Timer() {
			@Override
			public void run() {
				drawSomethingNew();
			}
		};
		timer.scheduleRepeating(1500);
	}

	public void drawSomethingNew() {

		// Get random coordinates and sizing
		int rndX = Random.nextInt(canvasWidth);
		int rndY = Random.nextInt(canvasHeight);
		int rndWidth = Random.nextInt(canvasWidth);
		int rndHeight = Random.nextInt(canvasHeight);

		// Get a random color and alpha transparency
		int rndRedColor = Random.nextInt(255);
		int rndGreenColor = Random.nextInt(255);
		int rndBlueColor = Random.nextInt(255);
		double rndAlpha = Random.nextDouble();

		CssColor randomColor = CssColor.make("rgba(" + rndRedColor + ", "
				+ rndGreenColor + "," + rndBlueColor + ", " + rndAlpha + ")");

		context.setFillStyle(randomColor);
		context.fillRect(rndX, rndY, rndWidth, rndHeight);
		context.fill();
	}
	private native static boolean isSupport()/*-{
		return $wnd.isFlashCanvasSupport();
	}-*/;

	private native static void initExCanvas()/*-{
		// CONTENTS OF EXCANVAS.JS HERE
		$wnd.initialisation();
   	}-*/;
}
